package com.perceptivesoftware.licensing.client.dialogs.useradmin.plugin.superadmin;

import java.util.ArrayList;
import java.util.List;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.perceptivesoftware.licensing.client.LicensingRPCFactory;
import com.perceptivesoftware.licensing.client.PerceptiveUISession;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.SecurityManagerView;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.callbackhandlers.AddCallbackHandler;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.callbackhandlers.ItemSelectedCallbackHandler;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.interfaces.Addable;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.interfaces.Parent;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.plugin.SecurityManagerNavItem;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.plugin.SecurityManagerPlugin;
import com.perceptivesoftware.licensing.client.dialogs.useradmin.plugin.user.UserNavItem;

public class SuperAdminRootPlugin extends SecurityManagerPlugin<SuperAdminRootNavItem> implements Parent, Addable {

	SuperAdminRootView sarv = new SuperAdminRootView();
	PerceptiveUISession session = PerceptiveUISession.getInstance();

	@Override
	public void init() {

	}

	@Override
	protected void itemSelected(@SuppressWarnings("unused") SuperAdminRootNavItem ani, ItemSelectedCallbackHandler isch) {
		isch.doneRendering();
	}

	@Override
	public SecurityManagerView getView() {
		return sarv;
	}

	@Override
	public String getIconStyle() {
		return "nav-icon-user-super";
	}

	@Override
	public List<SecurityManagerNavItem> getChildren(@SuppressWarnings("unused") SecurityManagerNavItem parent) {
		final ArrayList<SecurityManagerNavItem> returnusers = new ArrayList<SecurityManagerNavItem>();
		for (final UserNavItem userNavItem : PerceptiveUISession.getInstance().getAllUsers()) {
			if (userNavItem.getIsSuperAdmin()) {
				returnusers.add(userNavItem);
			}
		}
		return returnusers;
	}

	@Override
	public String getAddName() {
		return "Super Admin";
	}

	@Override
	public String getAddIconStyle() {
		return "nav-icon-user-add";
	}

	@Override
	public void add(String name, @SuppressWarnings("unused") SecurityManagerNavItem parent, final AddCallbackHandler ach) {
		LicensingRPCFactory.getSecurityService(true).createUser(name, null, true, new AsyncCallback<UserNavItem>() {

			@Override
			public void onFailure(@SuppressWarnings("unused") Throwable caught) {
				ach.addFailed("Does a user already exist with this username?");
			}

			@Override
			public void onSuccess(UserNavItem result) {
				ach.added(result);
			}
		});
	}

	@Override
	public Boolean canAdd(@SuppressWarnings("unused") SecurityManagerNavItem parent) {
		return session.isSuperAdmin();
	}

}
